<template>
  <div class="data-source-settings">
    <h2>{{ t('settings.dataSourceSettings') }}</h2>
    
    <el-form :model="dataSourceForm" label-position="top">
      <el-form-item :label="t('settings.dataSourceType')">
        <el-radio-group v-model="dataSourceForm.type" @change="handleDataSourceTypeChange">
          <el-radio :value="'local'">{{ t('settings.localSource') }}</el-radio>
          <el-radio :value="'remote'">{{ t('settings.remoteSource') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <div v-if="dataSourceForm.type === 'local'">
        <el-form-item :label="t('settings.localSavePath')">
          <el-input 
            v-model="dataSourceForm.localSavePath" 
            :placeholder="t('settings.localSavePathPlaceholder')"
            @blur="handleLocalPathChange"
          >
            <template #append>
              <el-button @click="handleSelectFolder('save')">
                {{ t('settings.selectFolder') }}
              </el-button>
            </template>
          </el-input>
          <div class="form-item-tip">{{ t('settings.localSavePathTip') }}</div>
          <div class="default-path-info" v-if="defaultPath">
            <span>{{ t('settings.defaultSavePath') }}: </span>
            <span class="default-path">{{ defaultPath }}</span>
          </div>
        </el-form-item>

        <el-form-item :label="t('settings.trashPath')">
          <el-input 
            v-model="dataSourceForm.trashPath" 
            :placeholder="t('settings.trashPathPlaceholder')"
            @blur="handleTrashPathChange"
          >
            <template #append>
              <el-button @click="handleSelectFolder('trash')">
                {{ t('settings.selectFolder') }}
              </el-button>
            </template>
          </el-input>
          <div class="form-item-tip">{{ t('settings.trashPathTip') }}</div>
          <div class="default-path-info" v-if="defaultTrashPath">
            <span>{{ t('settings.defaultTrashPath') }}: </span>
            <span class="default-path">{{ defaultTrashPath }}</span>
          </div>
        </el-form-item>
      </div>
      
      <div v-if="dataSourceForm.type === 'remote'">
        <el-form-item :label="t('settings.apiBaseUrl')">
          <el-input 
            v-model="dataSourceForm.apiBaseUrl" 
            :placeholder="t('settings.apiBaseUrlPlaceholder')"
            @blur="handleApiUrlChange"
          ></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-checkbox 
            v-model="dataSourceForm.useMockData" 
            @change="handleMockDataChange"
          >{{ t('settings.useMockData') }}（{{ t('settings.useMockDataTip') }}）</el-checkbox>
        </el-form-item>
      </div>
      
      <el-form-item>
        <el-alert 
          v-if="saveMessage" 
          :type="saveStatus ? 'success' : 'error'" 
          :title="saveMessage" 
          :closable="false" 
          show-icon
        ></el-alert>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { getConfig, updateDataSourceConfig } from '../../services/configService';
import { initMockData } from '../../services/mockService';

const { t } = useI18n();

// 表单数据
const dataSourceForm = reactive({
  type: 'local' as 'local' | 'remote',
  apiBaseUrl: 'http://localhost:8080/api',
  useMockData: true,
  localSavePath: '',
  trashPath: ''
});

// 保存信息
const saveMessage = ref('');
const saveStatus = ref(false);
const defaultPath = ref('');
const defaultTrashPath = ref('');

// 初始化数据
onMounted(async () => {
  try {
    const config = await getConfig();
    dataSourceForm.type = config.dataSource.type;
    dataSourceForm.apiBaseUrl = config.dataSource.apiBaseUrl;
    dataSourceForm.useMockData = config.dataSource.useMockData;
    dataSourceForm.localSavePath = config.dataSource.localSavePath || '';
    dataSourceForm.trashPath = config.dataSource.trashPath || '';
    
    // 如果是首次加载并且使用Mock数据模式，初始化Mock数据
    if (config.dataSource.type === 'remote' && config.dataSource.useMockData) {
      initMockData();
    }
    
    // 获取默认保存路径
    getDefaultSavePath();
    getDefaultTrashPath();
  } catch (error) {
    console.error('加载配置失败:', error);
    ElMessage.error(t('settings.loadFailed'));
  }
});

// 获取默认保存路径
async function getDefaultSavePath() {
  try {
    const result = await window.electronAPI.getDefaultPath();
    if (result && result.defaultPath) {
      defaultPath.value = result.defaultPath;
    }
  } catch (error) {
    console.error('获取默认路径失败:', error);
  }
}

// 获取默认垃圾路径
async function getDefaultTrashPath() {
  try {
    const result = await window.electronAPI.getDefaultTrashPath();
    if (result && result.defaultTrashPath) {
      defaultTrashPath.value = result.defaultTrashPath;
    }
  } catch (error) {
    console.error('获取默认垃圾路径失败:', error);
  }
}

// 处理选择文件夹
async function handleSelectFolder(type: 'save' | 'trash') {
  try {
    // 使用Electron的dialog API来选择文件夹
    const result = await window.electronAPI.selectFolder();
    if (result && !result.canceled && result.filePaths.length > 0) {
      if (type === 'save') {
        dataSourceForm.localSavePath = result.filePaths[0];
        // 保存新的路径
        await handleLocalPathChange();
      } else if (type === 'trash') {
        dataSourceForm.trashPath = result.filePaths[0];
        // 保存新的路径
        await handleTrashPathChange();
      }
    }
  } catch (error) {
    console.error('选择文件夹失败:', error);
    ElMessage.error(t('settings.selectFolderFailed'));
  }
}

// 处理本地保存路径变更
async function handleLocalPathChange() {
  if (dataSourceForm.type === 'local') {
    try {
      saveMessage.value = t('common.saving');
      
      // 保存配置
      const success = await updateDataSourceConfig(
        dataSourceForm.type,
        dataSourceForm.useMockData,
        dataSourceForm.apiBaseUrl,
        dataSourceForm.localSavePath,
        dataSourceForm.trashPath
      );
      
      if (success) {
        saveStatus.value = true;
        saveMessage.value = t('settings.dataSourceSaveSuccess');
        
        setTimeout(() => {
          saveMessage.value = '';
        }, 3000);
      } else {
        saveStatus.value = false;
        saveMessage.value = t('settings.dataSourceSaveFailed');
      }
    } catch (error) {
      console.error('保存配置失败:', error);
      saveStatus.value = false;
      saveMessage.value = t('settings.dataSourceSaveFailed');
    }
  }
}

// 处理垃圾路径变更
async function handleTrashPathChange() {
  if (dataSourceForm.type === 'local') {
    try {
      saveMessage.value = t('common.saving');
      
      // 保存配置
      const success = await updateDataSourceConfig(
        dataSourceForm.type,
        dataSourceForm.useMockData,
        dataSourceForm.apiBaseUrl,
        dataSourceForm.localSavePath,
        dataSourceForm.trashPath
      );
      
      if (success) {
        saveStatus.value = true;
        saveMessage.value = t('settings.dataSourceSaveSuccess');
        
        setTimeout(() => {
          saveMessage.value = '';
        }, 3000);
      } else {
        saveStatus.value = false;
        saveMessage.value = t('settings.dataSourceSaveFailed');
      }
    } catch (error) {
      console.error('保存配置失败:', error);
      saveStatus.value = false;
      saveMessage.value = t('settings.dataSourceSaveFailed');
    }
  }
}

// 处理数据源类型变更
async function handleDataSourceTypeChange() {
  try {
    saveMessage.value = t('common.saving');
    
    // 保存配置
    const success = await updateDataSourceConfig(
      dataSourceForm.type,
      dataSourceForm.useMockData,
      dataSourceForm.apiBaseUrl,
      dataSourceForm.localSavePath,
      dataSourceForm.trashPath
    );
    
    if (success) {
      saveStatus.value = true;
      saveMessage.value = t('settings.dataSourceSaveSuccess');
      
      // 如果切换到远程模式并且启用了Mock数据，初始化Mock数据
      if (dataSourceForm.type === 'remote' && dataSourceForm.useMockData) {
        initMockData();
      }
      
      setTimeout(() => {
        saveMessage.value = '';
      }, 3000);
    } else {
      saveStatus.value = false;
      saveMessage.value = t('settings.dataSourceSaveFailed');
    }
  } catch (error) {
    console.error('保存配置失败:', error);
    saveStatus.value = false;
    saveMessage.value = t('settings.dataSourceSaveFailed');
  }
}

// 处理API URL变更
async function handleApiUrlChange() {
  if (dataSourceForm.type === 'remote') {
    try {
      saveMessage.value = t('common.saving');
      
      // 保存配置
      const success = await updateDataSourceConfig(
        dataSourceForm.type,
        dataSourceForm.useMockData,
        dataSourceForm.apiBaseUrl,
        dataSourceForm.localSavePath,
        dataSourceForm.trashPath
      );
      
      if (success) {
        saveStatus.value = true;
        saveMessage.value = t('settings.dataSourceSaveSuccess');
        
        setTimeout(() => {
          saveMessage.value = '';
        }, 3000);
      } else {
        saveStatus.value = false;
        saveMessage.value = t('settings.dataSourceSaveFailed');
      }
    } catch (error) {
      console.error('保存配置失败:', error);
      saveStatus.value = false;
      saveMessage.value = t('settings.dataSourceSaveFailed');
    }
  }
}

// 处理Mock数据开关变更
async function handleMockDataChange() {
  try {
    saveMessage.value = t('common.saving');
    
    // 保存配置
    const success = await updateDataSourceConfig(
      dataSourceForm.type,
      dataSourceForm.useMockData,
      dataSourceForm.apiBaseUrl,
      dataSourceForm.localSavePath,
      dataSourceForm.trashPath
    );
    
    if (success) {
      saveStatus.value = true;
      saveMessage.value = t('settings.dataSourceSaveSuccess');
      
      // 如果启用了Mock数据，初始化Mock数据
      if (dataSourceForm.useMockData) {
        initMockData();
      }
      
      setTimeout(() => {
        saveMessage.value = '';
      }, 3000);
    } else {
      saveStatus.value = false;
      saveMessage.value = t('settings.dataSourceSaveFailed');
    }
  } catch (error) {
    console.error('保存配置失败:', error);
    saveStatus.value = false;
    saveMessage.value = t('settings.dataSourceSaveFailed');
  }
}
</script>

<style scoped>
.data-source-settings {
  padding: 16px;
}

.data-source-settings h2 {
  margin-bottom: 20px;
  font-size: 1.5rem;
}

.form-item-tip {
  font-size: 0.85rem;
  color: #909399;
  margin-top: 4px;
  line-height: 1.2;
}

.default-path-info {
  font-size: 0.85rem;
  color: #606266;
  margin-top: 8px;
  padding: 4px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  word-break: break-all;
}

.default-path {
  font-family: monospace;
  color: #409eff;
}
</style>